package com.xy.hms.config;

import com.xy.hms.service.UserServiceI;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @author xiaye
 * @create 2020-03-09-9:07
 */
@Configuration
public class ShiroConfig {
    /**
     * Subjecct 对象
     * 管理器
     * 连接资源
     *
     * ShiroFilterFactoryBean
     * DefaultWebSecurityManager
     * 创建realm 对象
     *
     */


    //ShiroFilterFactoryBean
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager")DefaultWebSecurityManager defaultWebSecurityManager){

        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        //设置安全管理器
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
        //添加shiro内置的过滤器
        /*
            anon:无需认证就可以访问
            authc：必须认证了才可以访问
            user：必须拥有记住我 功能才可以访问
            perms：拥有对某个资源的权限才可以访问
            role：拥有某个角色权限才可以访问
         */
        Map<String, String> filterMap  = new HashMap<>();
        //授权的才可以操作房间功能
        filterMap.put("/room/*","perms[room:all]");
        filterMap.put("/room","perms[room:all]");
        filterMap.put("/user/showAuths","perms[user:auth]");

        //认证了的人才可以访问这些，拦截器可以做到
//        filterMap.put("/room/*","authc");
//        filterMap.put("/room","authc");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);
        shiroFilterFactoryBean.setLoginUrl("/login.html");
        shiroFilterFactoryBean.setUnauthorizedUrl("/unAuth");

        return shiroFilterFactoryBean;
    }

    //DefaultWebSecurityManager
    @Bean(name = "securityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //关联userRealm
        securityManager.setRealm(userRealm);
        return securityManager;
    }

    //创建realm 对象
    @Bean(name = "userRealm")
    public UserRealm userRealm(){
        return new UserRealm();
    }

}
